import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
import { message } from 'antd';

// 后端API地址
const BASE_URL = 'http://1.15.22.194:8080';

// 创建axios实例
const request: AxiosInstance = axios.create({
  baseURL: BASE_URL,
  timeout: 10000, // 10秒超时
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
request.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 在发送请求之前做些什么
    
    // 添加认证token（如果有）
    const token = localStorage.getItem('admin_token');
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    
    // 添加时间戳防止缓存
    if (config.method === 'get') {
      config.params = {
        ...config.params,
        _t: Date.now(),
      };
    }
    
    console.log('Request:', config.method?.toUpperCase(), config.url, config.params || config.data);
    return config;
  },
  (error: AxiosError) => {
    console.error('Request Error:', error);
    message.error('请求配置错误');
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    // 对响应数据做点什么
    const { data } = response;
    
    console.log('Response:', response.config.url, data);
    
    // 如果后端返回的数据结构是 { code, message, data }
    if (data && typeof data === 'object' && 'code' in data) {
      if (data.code === 200 || data.code === 0) {
        // 成功
        return data;
      } else {
        // 业务错误
        const errorMsg = data.message || '请求失败';
        message.error(errorMsg);
        return Promise.reject(new Error(errorMsg));
      }
    }
    
    // 如果是直接返回数据（如Spring Boot默认格式）
    return data;
  },
  (error: AxiosError) => {
    // 对响应错误做点什么
    console.error('Response Error:', error);
    
    if (error.response) {
      const { status, data } = error.response;
      
      switch (status) {
        case 401:
          message.error('未授权，请重新登录');
          // 清除token并跳转到登录页
          localStorage.removeItem('admin_token');
          window.location.href = '/login';
          break;
        case 403:
          message.error('权限不足');
          break;
        case 404:
          message.error('请求的资源不存在');
          break;
        case 500:
          message.error('服务器内部错误');
          break;
        default:
          const errorMsg = (data as any)?.message || error.message || '请求失败';
          message.error(errorMsg);
      }
    } else if (error.request) {
      message.error('网络错误，请检查网络连接');
    } else {
      message.error('请求配置错误');
    }
    
    return Promise.reject(error);
  }
);

// 通用请求方法
export const api = {
  // GET请求
  get<T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> {
    return request.get(url, { params, ...config });
  },
  
  // POST请求
  post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return request.post(url, data, config);
  },
  
  // PUT请求
  put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return request.put(url, data, config);
  },
  
  // DELETE请求
  delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return request.delete(url, config);
  },
  
  // PATCH请求
  patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return request.patch(url, data, config);
  },
  
  // 文件上传
  upload<T = any>(url: string, file: File, onProgress?: (progress: number) => void): Promise<T> {
    const formData = new FormData();
    formData.append('file', file);
    
    return request.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress: (progressEvent) => {
        if (progressEvent.total && onProgress) {
          const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          onProgress(progress);
        }
      },
    });
  },
  
  // 文件下载
  download(url: string, filename?: string, params?: any): Promise<void> {
    return request.get(url, {
      params,
      responseType: 'blob',
    }).then((response) => {
      const blob = new Blob([response]);
      const downloadUrl = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = downloadUrl;
      a.download = filename || 'download';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(downloadUrl);
    });
  },
};

// Token管理
export const tokenManager = {
  // 设置token
  setToken(token: string): void {
    localStorage.setItem('admin_token', token);
  },
  
  // 获取token
  getToken(): string | null {
    return localStorage.getItem('admin_token');
  },
  
  // 移除token
  removeToken(): void {
    localStorage.removeItem('admin_token');
  },
  
  // 检查是否已登录
  isLoggedIn(): boolean {
    return !!this.getToken();
  },
};

// 导出默认实例
export default request;

// 导出基础URL供其他地方使用
export { BASE_URL };